package com.hx.thread;

/**
 * 计算质数的个数
 *
 * @author Minghua Chen
 * @since on 2020/7/24 9:06
 */
public class CalculatorPrimeNum implements Runnable {
    private static long current = 1;
    private static long numPrimes = 0L;

    @Override
    public void run() {

        System.out.printf("线程%s：start\n", Thread.currentThread().getName());
        long max = 100L;
        while (current < max) {
            if (isPrime(current)) {
                numPrimes++;
            }
            current++;
            System.out.println("当前的" + current);
        }
        System.out.printf("线程%s：end\n", Thread.currentThread().getName() + ":" + numPrimes);
    }

    /**
     * 判断当前数是否为质数
     *
     * @param current
     * @return
     */
    private boolean isPrime(long current) {
        if (current < 2) {
            return true;
        }
        for (int i = 2; i < current; i++) {
            if (current % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        CalculatorPrimeNum task = new CalculatorPrimeNum();
        // 创建一个线程组
        Thread[] threads = new Thread[10];
        // 线程状态
        Thread.State[] states = new Thread.State[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(task);
            // 偶数线程
//            if (i % 2 == 0) {
//                threads[i].setPriority(Thread.MAX_PRIORITY);
//            } else {
//                threads[i].setPriority(Thread.MIN_PRIORITY);
//            }
            threads[i].setName(i + "号线程");
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }
    }
}
